package org.webdb.webapp.readers;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.spi.HttpRequest;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.webdb.core.database.Record;
import org.webdb.core.database.SimpleRecord;

@Provider
public class FormRecordBodyReader implements MessageBodyReader<Record> {

    @Override
    public boolean isReadable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return MediaType.APPLICATION_FORM_URLENCODED_TYPE
                .isCompatible(mediaType) && type.isAssignableFrom(Record.class);
    }

    @Override
    public Record readFrom(Class<Record> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
            throws IOException, WebApplicationException {
        HttpRequest request = ResteasyProviderFactory
                .getContextData(HttpRequest.class);

        SimpleRecord record = new SimpleRecord();
        MultivaluedMap<String, String> parameters;
        for (String key : (parameters = request.getDecodedFormParameters())
                .keySet()) {
            record.setField(key, parameters.getFirst(key));
        }
        return record;
    }
}
